package sz.szsmk.citizencard.ui.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.content.FileProvider;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.chenenyu.router.annotation.Route;
import com.google.gson.Gson;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.kevin.crop.UCrop;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import jp.wasabeef.glide.transformations.CropCircleTransformation;
import kotlin.Unit;
import kotlin.jvm.functions.Function0;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import sz.szsmk.citizencard.R;
import sz.szsmk.citizencard.log.L;
import sz.szsmk.citizencard.model.network.bean.response.IUserInfo;
import sz.szsmk.citizencard.mvp.BasePresenter;
import sz.szsmk.citizencard.mvp.IUserInfoView;
import sz.szsmk.citizencard.mvp.presenter.UserInfoPresenter;
import sz.szsmk.citizencard.ui.dialogs.PrePermissionDialog;
import sz.szsmk.citizencard.ui.dzsmkavtivity.AppBaseActivity;
import sz.szsmk.citizencard.util.ACache;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.PermissionUtil;
import sz.szsmk.citizencard.util.StringUtils;
import sz.szsmk.citizencard.widget.GlideCircleTransform;

import static java.lang.String.valueOf;
import static sz.szsmk.citizencard.ui.activity.SelectImageActivity.CAMERA_REQUEST_CODE;
import static sz.szsmk.citizencard.ui.activity.SelectImageActivity.GALLERY_REQUEST_CODE;

/**
 * Copyright (c)2018
 * author: zdh
 * created on: 2018/7/9 20:20
 * description:
 */
@Route("userinfo")
public class UserInfoActivity extends AppBaseActivity implements View.OnClickListener {

    private Dialog dialog;

    private String url = Constant.BASE_URL + "app/uums/modifyUserInfo";
    private String phone;
    public static final int REQUEST_CODE_ASK_PERMISSIONS = 123;
    //判断是否修改了 昵称和头像
    boolean isChange = false;

    // 拍照临时图片
    private String mTempPhotoPath;
    // 剪切后图像文件
    private Uri mDestinationUri;
    //裁剪后图片最终保存路径
    private String imagePath;

    ImageView iv_head;

    RelativeLayout userinfo_icon;

    TextView tv_nickname;

    Button btn_save;

    TextView setting_title;

    ImageView back;

    RelativeLayout userinfo_nick;

    //暂时没用
    @Inject
    UserInfoPresenter presenter;

    @Override
    protected BasePresenter[] initPresenters() {
        return new BasePresenter[]{ presenter };
    }


    @Override
    protected CharSequence getTopTitle() {
        return null;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getComponent().inject(this);
        setContentView(R.layout.user_info_activity);

        iv_head = findViewById(R.id.iv_head);

        userinfo_icon  = findViewById(R.id.userinfo_icon);

        tv_nickname = findViewById(R.id.tv_nickname);

        btn_save = findViewById(R.id.btn_save);

        setting_title = findViewById(R.id.setting_title);

        back = findViewById(R.id.back);

        userinfo_nick = findViewById(R.id.userinfo_nick);


        initViews();
    }

    protected void initViews() {
        //初始化拍照的的地址  和 切图后的地址
        mDestinationUri = Uri.fromFile(new File(Constant.CACHEPATH_IMAGE, "cropImage.jpeg"));
        mTempPhotoPath = Constant.CACHEPATH_IMAGE + "photo.jpeg";
        String userInfo = ACache.get(this).getAsString("userinfo");
        Log.d("clark",userInfo);
        String url1 = "";
        if (!StringUtils.isEmpty(userInfo)) {
            IUserInfo.UserExBean mUserInfo = new Gson().fromJson(userInfo, IUserInfo.class).getUserEx();
            if (mUserInfo != null) {
                tv_nickname.setText(mUserInfo.getNick_name());
                url1 = mUserInfo.getPhoto_url();
                phone = mUserInfo.getMobile();
            }
        }
        if (url1 != null) {
            Glide.with(this)
                    .load(url1)
                    .override(100, 40)
                    .transform(new GlideCircleTransform(this))
                    .placeholder(R.mipmap.icon_head_default)
                    .into(iv_head);
        }

        iv_head.setOnClickListener(this);
        setting_title.setText("个人信息");
        btn_save.setOnClickListener(this);
        userinfo_icon.setOnClickListener(this);


        userinfo_nick.setOnClickListener(v -> {
            Intent intent = new Intent(UserInfoActivity.this, ModifyUserInfoActivity.class);
            startActivityForResult(intent, 1000);
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.back) {
            finish();
        } else if (id == R.id.userinfo_icon) {
            checkPermission();
        } else if (id == R.id.btn_save) {
            if (isChange) {
                upLoad();
            } else {
                finish();
            }
        }
    }

    private void upLoad() {
        //这里请求接口    nickname 和  图片 必须同时 上传 ，只上传一个 会失败
        iv_head.setDrawingCacheEnabled(true);
        Bitmap cache = iv_head.getDrawingCache();
        File files = compressImage(cache);
        String access_token = ACache.get(this).getAsString("access_token");
        Map<String, Object> params = new HashMap<>();
        params.put("access_token", access_token);
        if (phone != null) {
            params.put("userName", phone);
        }
        params.put("nickName", tv_nickname.getText().toString());
        OkHttpClient okHttpClient = new OkHttpClient();
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), files);
        builder.addFormDataPart("file", files.getName(), requestBody);

        if (params != null) {
            for (Map.Entry entry : params.entrySet()) {
                builder.addFormDataPart(valueOf(entry.getKey()), valueOf(entry.getValue()));
            }
        }
        Request request = new Request.Builder().url(url).post(builder.build()).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                L.e(Constant.TAG, e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(files.exists()){
                    files.delete();
                }

                L.e(Constant.TAG, response.message());
                finish();
            }
        });

    }

    public static File compressImage(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 500) {  //循环判断如果压缩后图片是否大于500kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            options -= 10;//每次都减少10
            bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            long length = baos.toByteArray().length;
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date(System.currentTimeMillis());
        String filename = format.format(date);
        File file = new File(Environment.getExternalStorageDirectory(), filename + "app_icon.png");
        try {
            FileOutputStream fos = new FileOutputStream(file);
            try {
                fos.write(baos.toByteArray());
                fos.flush();
                fos.close();
            } catch (IOException e) {
//                BAFLogger.e(TAG,e.getMessage());
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
//            BAFLogger.e(TAG,e.getMessage());
            e.printStackTrace();
        }
        recycleBitmap(bitmap);
        return file;
    }

    public static void recycleBitmap(Bitmap... bitmaps) {
        if (bitmaps == null) {
            return;
        }
        for (Bitmap bm : bitmaps) {
            if (null != bm && !bm.isRecycled()) {
                bm.recycle();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1000) {
            if (data != null) {
                Bundle bundle = data.getExtras();
                if (bundle != null) {
                    //处理代码在此地
                    String nickName = bundle.getString("nickName");// 得到子窗口ChildActivity的回传数据
                    tv_nickname.setText(nickName);
                    //修改了昵称
                    isChange = true;
                }
            }
        } else  if ( (requestCode ==  GALLERY_REQUEST_CODE || requestCode == CAMERA_REQUEST_CODE )&&  resultCode == RESULT_OK ) {
            switch (requestCode) {
                case CAMERA_REQUEST_CODE:   // 调用相机拍照
                    //三星 或 有些手机 打开自动拍照获取图片 当前的Activity会被销毁 有些对象 变成了null
                    if (mTempPhotoPath == null) {
                        mDestinationUri = Uri.fromFile(new File(Constant.CACHEPATH_IMAGE + File.separator, "cropImage.jpeg"));
                        mTempPhotoPath = Constant.CACHEPATH_IMAGE + "photo.jpeg";
                    }
                    File temp = new File(mTempPhotoPath);
                    startCropActivity(Uri.fromFile(temp));
                    break;
                case GALLERY_REQUEST_CODE:  // 直接从相册获取
                    startCropActivity(data.getData());
                    break;
            }
        }else if(requestCode== UCrop.REQUEST_CROP && resultCode==RESULT_OK){
            // 裁剪图片结果
            handleCropResult(data);
        }else if(resultCode==UCrop.RESULT_ERROR){
            // 裁剪图片错误
            handleCropError(data);
        }
    }


    //检查权限
    private void checkPermission() {

        if(XXPermissions.isGranted(this, Permission.READ_EXTERNAL_STORAGE,
                Permission.WRITE_EXTERNAL_STORAGE,Permission.CAMERA)){
            //正常打开
            openHeadDialog();
        }else{
            //自定义弹窗
            PrePermissionDialog dialog = PrePermissionDialog.Companion.newInstance(new Function0<Unit>() {
                @Override
                public Unit invoke() {
                    //授权
                    realPermission();
                    return null;
                }
            });
            dialog.show(this.getSupportFragmentManager(),"permission");
        }

    }

    private void realPermission(){
        XXPermissions.with(this)
                .permission(new String[]{
                        Permission.READ_EXTERNAL_STORAGE,
                        Permission.WRITE_EXTERNAL_STORAGE,Permission.CAMERA})
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all) {
                            openHeadDialog();
                        } else {
                            showToast("获取部分权限成功，但部分权限未正常授予");
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            showToast("被永久拒绝授权，请手动授予权限");
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(UserInfoActivity.this,permissions);
                        } else {
                            showToast("获取权限失败");
                        }
                    }

                });
    }

    private void openHeadDialog(){
        //打开 拍照、相册
        if (dialog == null) {
            dialog = new AlertDialog.Builder(UserInfoActivity.this).setItems(new String[]{"拍照",
                    "从相册选择"}, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (which == 0) {
                        takePhotoInternal();
                    } else {
                        pickFromGalleryInternal();
                    }
                }
            }).create();
        }
        if (!dialog.isShowing()) {
            dialog.show();
        }
    }

    //拍照
    //拍照会在指定的目录下 生成一个图片文件 然后把地址传入Intent 中
    //拍照后 直接操作这个文件
    //Android7.0 操作文件需要 google 收起了对私有目录的访问  需要配置一些内容
    //具体配置：http://blog.csdn.net/zz110753/article/details/60877594
    private void takePhotoInternal() {
        File newfile = new File(mTempPhotoPath);
        try {
            File path = new File(Constant.CACHEPATH_IMAGE);
            if(!path.exists()){
                path.mkdirs();
            }
            newfile.createNewFile();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Uri outputFileUri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName() + ".fileProvider", newfile);
        Intent takeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //添加权限
        takeIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        //下面这句指定调用相机拍照后的照片存储的路径
        takeIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
        startActivityForResult(takeIntent, CAMERA_REQUEST_CODE);
    }
    //打开相册
    private void pickFromGalleryInternal() {
        Intent pickIntent = new Intent(Intent.ACTION_PICK, null);
        // 如果限制上传到服务器的图片类型时可以直接写如："image/jpeg 、 image/png等的类型"
        pickIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(pickIntent, GALLERY_REQUEST_CODE);
    }

    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    public void startCropActivity(Uri uri) {
        UCrop.of(uri, mDestinationUri)
                .withAspectRatio(1, 1)
                .withMaxResultSize(512, 512)
                .withTargetActivity(CropActivity.class)
                .start(this);
    }

    /**
     * 处理剪切成功的返回值
     *
     * @param result
     */
    private void handleCropResult(Intent result) {
        //修改了图片
        isChange = true;
        Uri resultUri  = UCrop.getOutput(result);
        imagePath = resultUri.getPath();
        if (null != resultUri ) {
            Bitmap bitmap = null;
            try {
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), resultUri);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            Glide.with(UserInfoActivity.this)
                    .load(resultUri)
                    .skipMemoryCache( true )
                    .diskCacheStrategy( DiskCacheStrategy.NONE ) //跳过硬盘缓存
                    .placeholder(R.drawable.user_icon)
                    .error(R.drawable.user_icon)
                    .bitmapTransform(new CropCircleTransformation(UserInfoActivity.this))
                    .crossFade()
                    .into(iv_head);

        } else {
            Toast.makeText(this, "切图失败", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 处理剪切失败的返回值
     *
     * @param result
     */
    private void handleCropError(Intent result) {
        deleteTempPhotoFile();
        final Throwable cropError = UCrop.getError(result);
        if (cropError != null) {
            Toast.makeText(this, cropError.getMessage(), Toast.LENGTH_LONG).show();
        } else {
//            Toast.makeText(this, R.string.cropFieldStr, Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 删除拍照临时文件
     */
    private void deleteTempPhotoFile() {
        if (mTempPhotoPath == null) {
            mTempPhotoPath = Environment.getExternalStorageDirectory() + File.separator + "photo.jpeg";
        }

        File tempFile = new File(mTempPhotoPath);
        if (tempFile.exists() && tempFile.isFile()) {
            tempFile.delete();
        }
    }
}
